package com.hanson.service;

import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanson.Const;
import com.hanson.common.service.RedisService;
import com.hanson.common.util.BusinessUtil;
import com.hanson.common.util.QrCodeUtil;
import com.hanson.entity.AcctbkSeqBean;
import com.hanson.entity.ScoreSeqBean;
import com.hanson.entity.UserBean;
import com.hanson.mapper.AcctbkSeqBeanMapper;
import com.hanson.mapper.CouponsSeqBeanMapper;
import com.hanson.mapper.ScoreSeqBeanMapper;
import com.hanson.mapper.UserBeanMapper;
import com.hanson.param.MoneyScore;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@CacheConfig(cacheNames = "UserData")
public class UserService {
    @Autowired
    private UserBeanMapper userBeanMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ScoreSeqBeanMapper scoreSeqBeanMapper;
    @Autowired
    private AcctbkSeqBeanMapper acctbkSeqBeanMapper;
    @Autowired
    private CouponsSeqBeanMapper couponsSeqBeanMapper;
    @Autowired
    private QrCodeUtil qrCodeUtil;

    public List<UserBean> getDownloadUser(UserBean userBean) {
        if (!StringUtils.isEmpty(userBean.getUserType()) && "3".equals(userBean.getUserType())) {
            //合伙人搜索
            userBean.setIdentity("2");
            userBean.setUserType(null);
        }
        if (!StringUtils.isEmpty(userBean.getUserType()) && "4".equals(userBean.getUserType())) {
            //vip搜索
            userBean.setIdentity("1");
            userBean.setUserType(null);
        }
        List<UserBean> list = userBeanMapper.listUsersAll(userBean);
        if (!CollectionUtils.isEmpty(list)) {
            for (UserBean c : list) {
                c.setWebMoney(BusinessUtil.getWebAmount(c.getMoney()));
                if (c.getGender() == 1) {
                    c.setGenderName("男");
                } else if (c.getGender() == 2) {
                    c.setGenderName("未知");
                } else if (c.getGender() == 0) {
                    c.setGenderName("女");
                }

                if (c.getUserType().equals("2")) {
                    c.setUserType("掌柜");
                }
                if (c.getIsVip() == 1) {
                    c.setUserType(c.getUserType() + " VIP");
                }
                if (c.getIsSpread() == 1) {
                    c.setUserType(c.getUserType() + " 合伙人");
                }
                if (c.getUserType().equals("1") && c.getIsVip() == 0 && c.getIsSpread() == 0) {
                    c.setUserType("普通用户");
                }
            }
        }
        return list;
    }

    public Page<UserBean> listUsers(Page<UserBean> page, UserBean userBean) {
        if (!StringUtils.isEmpty(userBean.getUserType()) && "3".equals(userBean.getUserType())) {
            //合伙人搜索
            userBean.setIdentity("2");
            userBean.setUserType(null);
        }
        if (!StringUtils.isEmpty(userBean.getUserType()) && "4".equals(userBean.getUserType())) {
            //vip搜索
            userBean.setIdentity("1");
            userBean.setUserType(null);
        }
        List<UserBean> list = userBeanMapper.listUsers(page, userBean);
        if (!CollectionUtils.isEmpty(list)) {
            list.stream().forEach(c -> {
                c.setWebMoney(BusinessUtil.getWebAmount(c.getMoney()));
            });
        }
        return page.setRecords(list);
    }

    /**
     * 修改用户信息
     *
     * @param userBean
     */
    public void updateUser(UserBean userBean) {
        UserBean returnBean = userBeanMapper.selectByPrimaryKey(userBean.getId());
        if (null != returnBean) {
            returnBean.setUpdateDate(new Date());
            returnBean.setUserName(userBean.getNickName());
            returnBean.setNickName(userBean.getNickName());
            returnBean.setPhone(userBean.getPhone());
            returnBean.setPassword(userBean.getPassword());
            returnBean.setHeadImg(userBean.getHeadImg());
            userBeanMapper.updateByPrimaryKeySelective(returnBean);
            redisService.del(String.format(Const.USER_REDIS_KEY, returnBean.getOpenId()));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateMoneyScore(MoneyScore moneyScore) {
        UserBean returnBean = userBeanMapper.selectByPrimaryKey(moneyScore.getId());
        if (null != returnBean) {
            if (moneyScore.getMoney() != null && moneyScore.getMoney() != 0) {
                int money = Math.abs(moneyScore.getMoney());
                AcctbkSeqBean acctbkSeqBean = new AcctbkSeqBean();
                acctbkSeqBean.setOpenId(returnBean.getOpenId());
                acctbkSeqBean.setMoney(String.valueOf(money * 100));
                acctbkSeqBean.setCreateDate(new Date());
                if (moneyScore.getMoneyStatus() == 1) {
                    //增加
                    returnBean.setMoney(returnBean.getMoney() + money * 100);
                    acctbkSeqBean.setType(1);
                    acctbkSeqBean.setRemark("后台充值" + money + "元");
                } else {
                    returnBean.setMoney(returnBean.getMoney() - money * 100);
                    acctbkSeqBean.setType(2);
                    acctbkSeqBean.setRemark("后台扣除" + money + "元");
                }
                acctbkSeqBeanMapper.insert(acctbkSeqBean);
            }
            if (moneyScore.getScore() != null && moneyScore.getScore() != 0) {
                int score = moneyScore.getScore();
                ScoreSeqBean scoreSeqBean = new ScoreSeqBean();
                scoreSeqBean.setScore(score);
                scoreSeqBean.setOpenId(returnBean.getOpenId());
                scoreSeqBean.setCreateDate(new Date());
                if (moneyScore.getScoreStatus() == 1) {
                    //增加
                    scoreSeqBean.setType(1);
                    returnBean.setScore(returnBean.getScore() + score);
                    scoreSeqBean.setRemark("后台赠送" + score + "个积分");
                } else {
                    scoreSeqBean.setType(2);
                    returnBean.setScore(returnBean.getScore() - score);
                    scoreSeqBean.setRemark("后台扣除" + score + "个积分");
                }
                scoreSeqBeanMapper.insert(scoreSeqBean);
            }
            userBeanMapper.updateByPrimaryKeySelective(returnBean);
            redisService.del(String.format(Const.USER_REDIS_KEY, returnBean.getOpenId()));
        }
    }

    public UserBean addMiniUser(WxMaUserInfo wxMaUserInfo) {
        UserBean userBean = new UserBean();
        userBean.setCreateDate(new Date());
        userBean.setUserType("1");
        userBean.setGender(StringUtils.isEmpty(wxMaUserInfo.getGender()) ? 2 : Integer.parseInt(wxMaUserInfo.getGender()));
        userBean.setCountry(wxMaUserInfo.getCountry());
        userBean.setProvince(wxMaUserInfo.getProvince());
        userBean.setCity(wxMaUserInfo.getCity());
        userBean.setHeadImg(wxMaUserInfo.getAvatarUrl());
        userBean.setOpenId(wxMaUserInfo.getUnionId());
        userBean.setMaOpenId(wxMaUserInfo.getOpenId());
        userBeanMapper.insert(userBean);
        if (!StringUtils.isEmpty(wxMaUserInfo.getNickName())) {
            String nickNameSql = "update t_user set nick_name=?,user_name=? where open_id=?";
            jdbcTemplate.execute("set names utf8mb4");
            jdbcTemplate.update(nickNameSql, wxMaUserInfo.getNickName(), wxMaUserInfo.getNickName(), userBean.getOpenId());
        }
        return userBean;
    }

    /**
     * 新增用户
     */
    public UserBean addUser(WxMpUser wxMpUser) {
        UserBean userBean = new UserBean();
        userBean.setCreateDate(new Date());
        userBean.setUserType("1");
        userBean.setGender(wxMpUser.getSex());
        userBean.setCountry(wxMpUser.getCountry());
        userBean.setProvince(wxMpUser.getProvince());
        userBean.setCity(wxMpUser.getCity());
        userBean.setHeadImg(wxMpUser.getHeadImgUrl());
        userBean.setOpenId(wxMpUser.getUnionId());
        userBean.setMpOpenId(wxMpUser.getOpenId());
        userBeanMapper.insert(userBean);
        if (!StringUtils.isEmpty(wxMpUser.getNickname())) {
            String nickNameSql = "update t_user set nick_name=?,user_name=? where open_id=?";
            jdbcTemplate.execute("set names utf8mb4");
            jdbcTemplate.update(nickNameSql, wxMpUser.getNickname(), wxMpUser.getNickname(), userBean.getOpenId());
        }
        return userBean;
    }

    @Cacheable(key = "'List:'+#openId", unless = "#result == null")
    public UserBean selectByOpenId(String openId) {
        UserBean userBean = userBeanMapper.selectByOpenId(openId);
        if (null != userBean) {
            userBean.setWebMoney(BusinessUtil.getWebAmount(userBean.getMoney()));
            List<String> roles = new ArrayList<>();
            if (userBean.getIsVip() == 1) {
                roles.add("VIP");
            }
            if (userBean.getIsSpread() == 1) {
                roles.add("合伙人");
            }
            if (userBean.getUserType().equals("2")) {
                roles.add("掌柜");
            }
            userBean.setRoles(roles);
            Integer couponsNum = couponsSeqBeanMapper.countByUserIdAndType(userBean.getId(), 1);
            userBean.setCouponsNum(null == couponsNum ? 0 : couponsNum);
        }
        return userBean;
    }

    public UserBean selectByMpOpenId(String mpOpenId) {
        return userBeanMapper.selectByMpOpenId(mpOpenId);
    }

    public UserBean selectByMaOpenId(String maOpenId) {
        return userBeanMapper.selectByMaOpenId(maOpenId);
    }

    public UserBean selectByOpenIdOld(String openId) {
        return userBeanMapper.selectByOpenIdOld(openId);
    }

    public Integer updateOldSync(Integer isSync, Integer id) {
        return userBeanMapper.updateOldSync(isSync, id);
    }

    public int updateUserAll(UserBean userBean) {
        if (userBean.getIsSpread() == 1) {
            try {
                String miniUrl = qrCodeUtil.createQrCode(Const.CLIENT_MINI, userBean.getId());
                String h5Url = qrCodeUtil.createQrCode(Const.CLIENT_H5, userBean.getId());
                userBean.setSignDate(new Date());
                userBean.setUserSign(miniUrl + "," + h5Url);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("QRCode生成报错 userId=" + userBean.getId(), e);
            }
        }
        int result = userBeanMapper.updateByPrimaryKeySelective(userBean);
        if (result > 0) {
            redisService.del(String.format(Const.USER_REDIS_KEY, userBean.getOpenId()));
        }
        return result;
    }

    public int deleteUser(int id) {
        UserBean userBean = userBeanMapper.selectByPrimaryKey(id);
        if (null != userBean) {
            redisService.del(String.format(Const.USER_REDIS_KEY, userBean.getOpenId()));
            return userBeanMapper.deleteByPrimaryKey(id);
        }
        return 0;
    }

    public Integer countByOpenId(String openId) {
        Integer result = userBeanMapper.countByOpenId(openId);
        return null == result ? 0 : result;
    }

    public UserBean selectById(String id) {
        UserBean userBean = userBeanMapper.selectByPrimaryKey(Integer.parseInt(id));
        if (null != userBean) {
            userBean.setWebMoney(BusinessUtil.getWebAmount(userBean.getMoney()));
        }
        return userBean;
    }

    public UserBean getByNameAndPwd(String userName, String password) {
        List<UserBean> list = userBeanMapper.selectByUserNameAndPwd(userName, password);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    public int statisUser(int type) {
        return userBeanMapper.statisUser(type);
    }

    public int updateBeastTeam(int bestTeam, int id) {
        return userBeanMapper.updateBestTeam(bestTeam, id);
    }
}
